<!--
  * 项目信息表
  *
  * @Author:    yurui
  * @Date:      2024-07-01 16:39:11
  * @Copyright  shjz
-->
<template>
  <a-modal :title="form.id ? '编辑' : '添加'" style="width: 1000px" v-model:open="visibleFlag" @close="onClose" :maskClosable="false">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 7 }">
      <a-row>
        <a-col :span="12">
          <a-form-item style="" label="项目名称" name="projectName">
            <a-input style="width: 550px" v-model:value="form.projectName" placeholder="项目名称" />
          </a-form-item>
          <!-- 地址概述 -->
          <a-form>
            <a-form-item style="width: 845px; margin-left: 70px" label="施工地址" name="address">
              <a-input v-model:value="form.address" placeholder="施工地址" />
            </a-form-item>
            <a-form-item style="width: 845px; margin-left: 70px" label="项目概述" name="description">
              <a-input v-model:value="form.description" placeholder="项目概述" />
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
    </a-form>
    <!-- -------------------------------------- -->
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 7 }">
      <a-row>
        <a-col :span="12">
          <a-form-item label="客户名称" name="customerName">
            <a-input style="width: 300px" v-model:value="form.customerName" placeholder="客户名称" />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="合同金额" name="contractAmount">
            <a-input-number style="width: 300px" v-model:value="form.contractAmount" placeholder="合同金额" />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="立项日期" name="approveDate">
            <a-date-picker show-time valueFormat="YYYY-MM-DD HH:mm:ss" v-model:value="form.approveDate" style="width: 300px" placeholder="立项日期" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="竣工日期" name="planEndDate">
            <a-date-picker show-time valueFormat="YYYY-MM-DD HH:mm:ss" v-model:value="form.planEndDate" style="width: 300px" placeholder="结束日期" />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="项目负责人" name="projectLeaderId">
            <a-select v-model:value="form.projectLeaderId" placeholder="项目负责人" :allowClear="true" style="width: 300px">
              <a-select-option v-for="item in dictValueList" :key="item" :value="item.employeeId">
                {{ item.actualName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <!-- 查看文件 -->
        <a-col :span="12">
          <a-form-item label="合同文件" name="contractAmount">
            <a-button type="primary" @click="showUploadModal" size="small">
              <template #icon><cloud-upload-outlined /></template>上传文件
            </a-button>
            <a-button style="margin-left: 10px" type="primary" size="small" @click="viewFile">查看文件</a-button>
          </a-form-item>
          <a-modal v-model:open="uploadModalFlag" title="上传文件" @onCancel="hideUploadModal" @ok="hideUploadModal">
            <FileUpload
              list-type="text"
              :maxUploadSize="5"
              buttonText="点击上传文件"
              :defaultFileList="[]"
              :multiple="true"
              :folder="FILE_FOLDER_TYPE_ENUM.COMMON.value"
              @change="fileChange"
            />
          </a-modal>
        </a-col>
      </a-row>
    </a-form>

    <!-- 新添table表格(vxe )-->
    <div style="display: none">
      <vxe-toolbar>
        <template #buttons>
          <vxe-button style="background-color: #1677ff; color: #fff; border: none; outline: none" @click="insertEvent()"> 新增单行 </vxe-button>
          <vxe-button @click="insertEvent(-1)">在最后行插入</vxe-button>
          <vxe-button style="background-color: red; color: #fff; border: none; outline: none" @click="removeSelectRowEvent"> 删除选中 </vxe-button>
          <vxe-button @click="saveEvent">保存</vxe-button>
        </template>
      </vxe-toolbar>

      <vxe-table
        border
        show-overflow
        keep-source
        ref="tableRef"
        max-height="400"
        :data="tableData"
        :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }"
      >
        <vxe-column type="checkbox" width="60" />
        <vxe-column type="seq" width="70" />
        <vxe-column field="name" title="任务名称" :edit-render="{ autofocus: '.vxe-input--inner', defaultValue: '任务名称' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.name" type="text" />
          </template>
        </vxe-column>

        <!-- -------------------------------- -->
        <vxe-column field="sex" title="任务负责人" :edit-render="{}">
          <!-- 显示在下拉框上 -->
          <template #default="{ row }">
            <span>{{ formatSex(row) }}</span>
          </template>
          <!-- 编辑选择 -->
          <template #edit="{ row }">
            <vxe-select v-model="row.sex" transfer>
              <vxe-option v-for="item in dictValueList" :key="item" :value="item.employeeId" :label="item.actualName" />
            </vxe-select>
          </template>
        </vxe-column>

        <vxe-column field="date12" title="立项日期" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input v-model="row.date12" type="date" />
          </template>
        </vxe-column>
        <vxe-column field="date13" title="结束日期" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input v-model="row.date13" type="date" />
          </template>
        </vxe-column>
      </vxe-table>
    </div>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>

  <a-modal v-model:open="fileopen" title="文件查看" @ok="handleOk" style="width: 1000px; height: 600px">
    <div>
      <!-- <iframe :src="url" width="100%" height="700px" border="0" /> -->
      <iframe :src="fileUrl" style="width: 900px; height: 600px" ></iframe>
    </div>
  </a-modal>
</template>
<script setup>
  import { SmileOutlined, DownOutlined } from '@ant-design/icons-vue';
  import { reactive, ref, nextTick, onMounted } from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { projectApi } from '/@/api/business/project/project-api';
  import { smartSentry } from '/@/lib/smart-sentry';
  import DictSelect from '/@/components/support/dict-select/index.vue';
  import { dictApi } from '/src/api/support/dict-api';
  import { fileApi } from '/src/api/support/file-api';
  import FileUpload from '/@/components/support/file-upload/index2.vue';
  import { FILE_FOLDER_TYPE_ENUM } from '/@/constants/support/file-const';
  // import { SavetableContent } from '/src/api/support/dict-api';
  // 新增弹框里面的table表格
  import { VxeUI } from 'vxe-table';
  const tableRef = ref();
  const tableData = ref([]);
  // ------------- 上传文件 --------------------
  const uploadModalFlag = ref(false);

  function showUploadModal() {
    // console.log(222)
    uploadModalFlag.value = true;
    console.log(uploadModalFlag);
  }
  function hideUploadModal() {
    uploadModalFlag.value = false;
  }
  // 点击查看文件
  const viewFile = async (fileKey) => {
    if (form.id) {
      fileKey.value = form.fileKey;
      fileUrl.value = 'http://10.10.1.27:1024/upload/' + form.fileKey;
    }
    fileopen.value = true;
  };

  const fileUrl = ref('');
  const fileKey = ref('');
  const fileChange = async (file) => {
    console.log(file);
    // formDefault.fileId = file[0].fileId
    form.fileId = file[0].fileId;
    fileKey.value = file[0].fileKey;
    fileUrl.value = 'http://10.10.1.27:1024/upload/' + file[0].fileKey;
  };
  const fileopen = ref(false);

  const handleOk = (e) => {
    console.log(e);
    fileopen.value = false;
  };

  // 任务负责人
  const formatSex = (row) => {
    console.log(row);
    if (!row.sex) {
      return;
    }
    const obj = dictValueList.value.filter((e) => {
      return e.employeeId == row.sex;
    });
    return obj[0].actualName;
  };

  const insertsEvent = async () => {
    const $table = tableRef.value;
    if ($table) {
      const records = [];
      const { row: newRow } = await $table.insertAt(records, -1);
      await $table.setEditCell(newRow, 'name');
    }
  };

  // 新增/在最后一行插入
  const insertEvent = async (row) => {
    const $table = tableRef.value;
    if ($table) {
      const record = {
        // 获取当前日期
        date12: new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDay(),
        date13: new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDay(),
      };
      const { row: newRow } = await $table.insertAt(record, row);
      await $table.setEditCell(newRow, 'name');
    }
  };
  // 删除选中
  const removeSelectRowEvent = () => {
    const $table = tableRef.value;
    if ($table) {
      $table.removeCheckboxRow();
    }
  };
  // 项目人id
  const dictValueList = ref([]);
  async function queryDict() {
    let res = await dictApi.ProjecPersonid();
    dictValueList.value = res.data;
  }

  onMounted(() => {
    queryDict();
    // queryList();
  });
  // 保存抽屉里的表格内容
  const saveEvent = (param) => {
    const $table = tableRef.value;
    if ($table) {
      const { insertRecords, removeRecords, updateRecords } = dictApi.SavetableContent();
      VxeUI.modal.alert(`insertRecords=${insertRecords.length} removeRecords=${removeRecords.length} updateRecords=${updateRecords.length}`);
    }
  };

  const emits = defineEmits(['reloadList']);
  // ----------显示与隐藏 -----
  // 是否显示
  const visibleFlag = ref(false);

  function show(record) {
    Object.assign(form, formDefault);
    if (record && !_.isEmpty(record)) {
      Object.assign(form, record);
    }

    visibleFlag.value = true;
    nextTick(() => {
      formRef.value.clearValidate();
    });
  }

  function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
  }

  // -------表单 ----------
  // 组件ref
  const formRef = ref();

  const formDefault = {
    id: undefined,
    projectName: undefined, //项目名称
    approveDate: undefined, //立项日期
    // FileTable: undefined, //文件表id（连表t_file取file_id、file_name）
    fileId: undefined,
    contractAmount: undefined, //合同金额
    customerName: undefined, //客户名称
    projectLeaderId: undefined, //项目负责人id
    planEndDate: undefined, //计划竣工日期
    address: undefined, //施工地址
    description: undefined, //项目概述
  };

  let form = reactive({ ...formDefault });

  const rules = {
    projectName: [{ required: true, message: '项目名称 必填' }],
    approveDate: [{ required: true, message: '立项日期 必填' }],
    // FileTable: [{ required: true, message: '文件表id 必填' }],
    contractAmount: [{ required: true, message: '合同金额 必填' }],
    customerName: [{ required: true, message: '客户名称 必填' }],
    projectLeaderId: [{ required: true, message: '项目负责人id 必填' }],
    planEndDate: [{ required: true, message: '运维结束日期 必填' }],
  };
  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields();
      save();
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show();
    try {
      form.fileUrl = fileKey.value;
      if (form.id) {
        await projectApi.update(form);
      } else {
        await projectApi.add(form);
      }
      message.success('操作成功');
      emits('reloadList');
      onClose();
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }

  defineExpose({
    show,
  });
</script>
<!-- <style>
element.style{

}
</style> -->
